<template>
    <!-- 配送地址 -->
    <div class="order-address-info">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
            <el-form-item label="收货人" prop="receiver">
                <el-input
                    :disabled="isDisabled"
                    class="w420"
                    maxlength="20"
                    v-model.trim="form.receiver"
                    show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input :disabled="isDisabled" class="w420" v-model.trim="form.mobile"></el-input>
            </el-form-item>
            <el-form-item label="所在地区" prop="area">
                <el-cascader
                    :disabled="isDisabled"
                    class="w420"
                    v-model="form.area"
                    placeholder="请选择省市区"
                    :options="state.addressList"
                    :props="defaultProps"
                    @change="handleChange" />
            </el-form-item>
            <el-form-item label="详细地址" prop="street">
                <div class="align_center">
                    <el-input
                        :disabled="isDisabled"
                        v-model.trim="form.street"
                        class="w420"
                        maxlength="100"
                        show-word-limit></el-input>
                </div>
            </el-form-item>
            <div class="form-footer">
                <el-button :disabled="isDisabled" type="primary" @click="saveHandler">保存</el-button>
            </div>
        </el-form>
    </div>
</template>

<script setup>
import { ref, unref, reactive, computed, onMounted, onActivated, onDeactivated, onUnmounted } from 'vue';
import request from '@/request';
import { ElMessage } from 'element-plus';
import { cloneDeep } from '@/commons/utils';
import store from '@/store/index';
import { setLayout, resetLayout } from '@/hooks/layout';

const useAuth = store.useAuthStore();
const permissions = useAuth.permissions;
const isDisabled = computed(() => {
    return !permissions.has('delivery_management:edit_sales_address');
});

const formRef = ref();
const form = reactive({
    receiver: '', //店铺收货人姓名
    mobile: '', //收货人手机号
    street: '', //详细地址
    provinceId: 1, // '所在地区省份id',
    cityId: '', // '所在地区城市id',
    areaId: 1, // '所在地区县区id',
    streetId: '' // '所在地区乡镇id',
});
const rules = {
    receiver: [{ required: true, message: '请填写收货人' }],
    mobile: [
        { required: true, message: '请填写手机号' },
        { pattern: /^1[3-9][0-9]{9}$/, message: '请输入正确手机号' }
    ],
    area: [{ required: true, message: '请填写所在地区', trigger: 'change' }],
    street: [{ required: true, message: '请填写详细地址' }]
};

const state = reactive({
    addressList: [],
    address: ''
});
/* 获取地区列表 */
const defaultProps = {
    emitPath: true,
    label: 'name',
    value: 'id'
};

// 新增/编辑表单
const saveHandler = async () => {
    // todo:接口
    if (!unref(formRef)) return;
    await unref(formRef).validate(async (valid, fields) => {
        if (valid) {
            const _form = cloneDeep(form);
            delete _form.area;
            const { code } = await request('refundAddressSave', { ..._form, saveType: 'address' });
            if (code !== 0) {
                return;
            }
            ElMessage({
                type: 'success',
                message: '保存成功'
            });
        } else {
            unref(formRef).scrollToField(Object.keys(fields)?.[0]);
        }
    });
};

const handleChange = val => {
    const [provinceId, cityId, areaId] = val || [];
    form.provinceId = provinceId;
    form.cityId = cityId;
    form.areaId = areaId;
};

const getAddressDetail = async () => {
    const { data } = await request('refundAddressInfo');
    const _data = data || {};
    Object.keys(form).forEach(key => {
        form[key] = _data[key];
    });
    form.id = _data.id;
    form.area = _data.provinceId && _data.cityId && _data.areaId ? [_data.provinceId, _data.cityId, _data.areaId] : [];
    form.streetId = form.streetId === null ? '' : form.streetId;
};

const getAddressList = async () => {
    const { data } = await request('regionServ', { level: 3 });
    if (Array.isArray(data)) {
        data.splice(0, 1);
        state.addressList = data;
    }
};

onMounted(() => {
    getAddressDetail();
    getAddressList();
    // setLayout();
});

onUnmounted(() => {
    // resetLayout();
});

onActivated(() => {
    // setLayout();
});
onDeactivated(() => {
    // resetLayout();
});
</script>

<style lang="scss">
.order-address-info {
    .w420 {
        width: 420px;
    }
}
</style>
<style lang="scss" scoped src="./index.scss"></style>
